package cn.shyouchi.wuguanjia.android.ui.meetting.launch;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.meet.MeetApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.ui.meetting.common.MeetPerson;
import cn.shyouchi.wuguanjia.android.ui.meetting.common.SelMeetPersonActivity;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import cn.shyouchi.wuguanjia.android.widget.dialog.TimePickerDialogFragment;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static cn.shyouchi.wuguanjia.android.ui.meetting.common.SelMeetPersonActivity.REQ_CODE_DEPARTMENT;
import static cn.shyouchi.wuguanjia.android.ui.meetting.common.SelMeetPersonActivity.REQ_CODE_HOLDER;
import static cn.shyouchi.wuguanjia.android.ui.meetting.common.SelMeetPersonActivity.REQ_CODE_PERSON;
import static cn.shyouchi.wuguanjia.android.ui.meetting.common.SelMeetPersonActivity.REQ_CODE_RECORDER;
import static cn.shyouchi.wuguanjia.android.ui.meetting.common.SelMeetPersonActivity.RES_CODE_SUCCESS;

public class LaunchMeetActivity extends BaseActivity {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.et_meet_name)
    EditText mEtMeetName;
    @BindView(R.id.ra_meet_type_day)
    RadioButton mRaMeetTypeDay;
    @BindView(R.id.ra_meet_type_single)
    RadioButton mRaMeetTypeSingle;
    @BindView(R.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R.id.et_meet_addr)
    EditText mEtMeetAddr;
    @BindView(R.id.person_info_next1)
    ImageView mPersonInfoNext1;
    @BindView(R.id.img_add_person)
    ImageView mImgAddPerson;
    @BindView(R.id.rv_persons)
    RecyclerView mRvPersons;
    @BindView(R.id.person_info_next2)
    ImageView mPersonInfoNext2;
    @BindView(R.id.et_meet_purpose)
    EditText mEtMeetPurpose;
    @BindView(R.id.et_meet_agenda)
    EditText mEtMeetAgenda;
    @BindView(R.id.tv_holder)
    TextView mTvHolder;
    @BindView(R.id.tv_recorder)
    TextView mTvRecorder;


    MeetPerson holder;
    MeetPerson recorder;

    List<MeetPerson> mMeetPersons = new ArrayList<>();

    LaunchMeetPersonAdapter mMeetPersonAdapter;





    MenuItem mSubMenuItem;


    MeetApi mMeetApi;


    @Override
    public int initContentView() {
        return R.layout.activity_launch_meet;
    }

    @Override
    public void initInjector() {
        mMeetApi = new MeetApi(mContext);

    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());
        mRaMeetTypeSingle.setChecked(true);
        mMeetPersonAdapter = new LaunchMeetPersonAdapter(mMeetPersons);
        mRvPersons.setAdapter(mMeetPersonAdapter);
        mRvPersons.setLayoutManager(new LinearLayoutManager(mContext));

        mRaMeetTypeSingle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mTvEndTime.setText("");
                mTvStartTime.setText("");
            }
        });

    }


    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @OnClick({R.id.tv_holder, R.id.img_add_person, R.id.tv_recorder})
    public void onClick(View view) {

        Intent intent = new Intent(mContext, SelMeetPersonActivity.class);
        switch (view.getId()) {
            case R.id.tv_holder:
                intent.putExtra("single", true);
                startActivityForResult(intent, REQ_CODE_HOLDER);
                break;
            case R.id.img_add_person:
                intent.putExtra("single", false);
                startActivityForResult(intent, REQ_CODE_PERSON);
                break;
            case R.id.tv_recorder:
                intent.putExtra("single", true);
                startActivityForResult(intent, REQ_CODE_RECORDER);
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQ_CODE_HOLDER && resultCode == RES_CODE_SUCCESS) {
            holder = data.getParcelableExtra("data");
            if (holder != null) {
                mTvHolder.setText(holder.getName());
            }

        } else if (requestCode == REQ_CODE_PERSON && resultCode == RES_CODE_SUCCESS) {
            mMeetPersons.clear();
            List<MeetPerson> persons = data.getParcelableArrayListExtra("data");
            mMeetPersons.addAll(persons);
            mMeetPersonAdapter.notifyDataSetChanged();


        } else if (requestCode == REQ_CODE_RECORDER && resultCode == RES_CODE_SUCCESS) {
            recorder = data.getParcelableExtra("data");
            if (recorder != null) {
                mTvRecorder.setText(recorder.getName());
            }
        } else if (requestCode == REQ_CODE_DEPARTMENT && resultCode == RES_CODE_SUCCESS) {
            MeetPerson department = data.getParcelableExtra("data");

            if (department != null) {
                submitData(department.getId());
            }

        }
    }


    private void submitData(int deId) {
        Map<String, Object> params = new HashMap<>();
        params.put("name", mEtMeetName.getText().toString());
        params.put("time_type", mRaMeetTypeDay.isChecked() ? 1 : 2);
        params.put("start", mTvStartTime.getText());
        params.put("end", mTvEndTime.getText());
        params.put("address", mEtMeetAddr.getText().toString());
        params.put("host", holder.getId());
        params.put("recorder", recorder.getId());
        params.put("meeting_purpose", mEtMeetPurpose.getText().toString());
        params.put("meeting_agenda", mEtMeetAgenda.getText().toString());
        params.put("userid", getPersonId());
        params.put("department_id", deId);

        mMeetApi.meetAdd(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<BaseRequestResult<String>>(mContext) {
                    @Override
                    public void onNext(BaseRequestResult<String> req) {
                        ToastUtil.showToast(req.getResultMessage());
                        finish();
                    }
                });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mSubMenuItem = menu.add("提交");
        mSubMenuItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item == mSubMenuItem) {
            if (judgeData()) {
                Intent intent = new Intent(mContext, SelMeetPersonActivity.class);
                intent.putExtra("single", true);
                intent.putExtra("selDepartment", true);
                startActivityForResult(intent, REQ_CODE_DEPARTMENT);
            }
        }

        return super.onOptionsItemSelected(item);
    }


    private List<Integer> getPersonId() {
        List<Integer> ids = new ArrayList<>();
        for (MeetPerson p : mMeetPersons) {
            ids.add(p.getId());
        }
        return ids;
    }


    private boolean judgeData() {

        if (TextUtils.isEmpty(mEtMeetName.getText().toString())) {
            ToastUtil.showToast("请填写会议名");
            return false;
        }

        if (TextUtils.isEmpty(mEtMeetAddr.getText().toString())) {
            ToastUtil.showToast("请填写会议地址");
            return false;
        }
        if (TextUtils.isEmpty(mEtMeetPurpose.getText().toString())) {
            ToastUtil.showToast("请填写会议目的");
            return false;
        }
        if (TextUtils.isEmpty(mEtMeetAgenda.getText().toString())) {
            ToastUtil.showToast("请填写会议议程");
            return false;
        }

        if (TextUtils.isEmpty(mTvStartTime.getText().toString())) {
            ToastUtil.showToast("请选择开始时间");
            return false;
        }

        if (TextUtils.isEmpty(mTvEndTime.getText().toString())) {
            ToastUtil.showToast("请选择结束时间");
            return false;
        }

        if (holder == null) {
            ToastUtil.showToast("请选择主持人");
            return false;
        }

        if (recorder == null) {
            ToastUtil.showToast("请选择记录人");
            return false;
        }

        if (mMeetPersons.isEmpty()) {
            ToastUtil.showToast("请选择参会人员");
            return false;
        }
        return true;
    }


    public void showTimePicker(final TextView tv, String title) {
        TimePickerDialogFragment mTimePickerDialog;
        mTimePickerDialog = new TimePickerDialogFragment(getSupportFragmentManager(), title, "");
        mTimePickerDialog.setOnTimePickedListener(new TimePickerDialogFragment.onTimePickedListener() {
            @Override
            public void onPicked(String time) {
                tv.setText(time);
            }
        });

        if (mRaMeetTypeDay.isChecked()) {
            mTimePickerDialog.showDialog();
        } else {
            mTimePickerDialog.showWhitDate();
        }

    }


    @OnClick({R.id.tv_start_time, R.id.tv_end_time})
    public void onTimeClick(View view) {
        switch (view.getId()) {
            case R.id.tv_start_time:
                showTimePicker((TextView) view, "选择开始时间");
                break;
            case R.id.tv_end_time:
                showTimePicker((TextView) view, "选择结束时间");
                break;
        }
    }
}
